var QQMapWX = require('./qqmap-wx-jssdk');
var qqmapsdk = new QQMapWX({
  key: 'M3WBZ-CL7LI-556GU-5OXUX-JLYOK-JXFL5' // 必填
});
//时间格式 年-月-日 小时:分钟:秒钟
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
//时间格式：月/日
const todayTiem = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[month, day].map(formatNumber).join('/')}`
}

//时间字符串拆分 年-月-日 拆分成 月/日
const tiemString = (data) => {
  let stringData = data.split('-')[1] + '/' + data.split('-')[2]
  return stringData
}

//时间段数据返回
const timeState = (activityFlag, activityTime, nowTime) => {
  let countMap = []
  let temp = activityTime
  let list = {}
  if (activityFlag !== 1) {
    for (let j = 0; j < temp.length; j++) {
      countMap.push({
        startTime: temp[j][0],
        endTime: temp[j][1]
      })
    }
    list.temp = activityTime.map(x => activityFlag)
    list.countMap = countMap
    return list
  }
  // 循环判断时间段
  for (let i = 0; i < temp.length; i++) {
    countMap.push({
      startTime: temp[i][0],
      endTime: temp[i][1]
    })
    if (temp[i][0] < nowTime) {
      if (temp[i][1] > nowTime) {
        temp[i] = 1
      } else {
        temp[i] = 0
      }
    } else {
      temp[i] = 2
    }
  }
  list.temp = temp
  list.countMap = countMap
  // 返回每个时段的标识 0 已经结束   1 进行中  2 未开始
  return list
}

//当前定位数据
const locationData = () => {
  let locationInfo = {}
  let locationVal = ''
  wx.getLocation({
    type: 'gcj02',
    success(res) {
      locationVal = res.latitude + ',' + res.longitude
      qqmapsdk.reverseGeocoder({
        location: locationVal,
        success: function (res) {
          locationInfo = res.result
          wx.setStorageSync('locationInfo', res.result)
          wx.setStorageSync('currentDate', new Date().getHours())
        }
      })
    }
  })
}

//选择当前定位数据
const chooseLocationData = (locationVal) => {

  qqmapsdk.reverseGeocoder({
    location: locationVal,
    success: function (res) {
      var locationInfo = res.result
      wx.setStorageSync('locationInfo', locationInfo)
      wx.setStorageSync('currentDate', new Date().getHours())
    }
  })
}

//通过地址解析
const reverseLocationData = (data) => {
  let location=""
  // 调用接口
  qqmapsdk.search({
    keyword: data,
    success: function (res) {
      console.log(res)
      location=res.data[0].location.lat+','+res.data[0].location.lng
      wx.setStorageSync('reverseLocationData', res.data[0].location.lat+','+res.data[0].location.lng)
    },
    fail: function (res) {
      // console.log(res);
    },
    complete: function (res) {
      // console.log(res);
    }
  });
}


//时间 --- 年/月/日
const formatDate = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return year + "-" + month + "-" + day
}

const formatDateymd = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  if(month<10){
    month='0'+month
  }
  if(day<10){
    day='0'+day
  }
  
  return year + "-" + month + "-" + day
}

//日期比对
const isValidDateRange=(startDate, endDate)=>{
  // 将日期字符串转换为日期对象
  var start = new Date(startDate);
  var end = new Date(endDate);
 
  // 如果开始日期在结束日期之后，则不合理
  //console.log(start.getTime(),end.getTime())
  if (start.getTime() > end.getTime()) {
    return false;
  }else{
    return true;
  }
  
}

//两个日期相距多少天
const isValidDateRangeDay=(startDate, endDate)=>{
  // 将日期字符串转换为日期对象
  var oneDay = 24 * 60 * 60 * 1000;
  var start = new Date(startDate);
  var end = new Date(endDate);
  return Math.round(Math.abs((end - start) / oneDay));

}
 


//时间 --- 年,月,日
const formatGetDate = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return {
    year: year,
    month: month,
    day: day
  }
}

//时间 --- 月份天数
const formatDateDays = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var mm = new Date(year, month, 0).getDate()
  return mm
}


//时间字符串拼接--- xxxx年xx月xx日
const formatDateSplicing = (date) => {
  var frontData = date.split(' ')[0]
  var completeData = frontData.split('-')[0] + '年' + frontData.split('-')[1] + '月' + frontData.split('-')[2] + '日'
  return completeData
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

//计算右侧胶囊位置
const capsuleData = () => {
  let infoData = {}
  // 1.获取屏幕可使用宽度
  let windowWidth = wx.getSystemInfoSync().windowWidth;
  // 2.获取状态栏高度
  const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
  // // 3.获取胶囊按钮位置信息
  const menuButton = wx.getMenuButtonBoundingClientRect();
  // 4.计算出导航栏高度  换算成rpx
  let navHeight = (menuButton.height + (menuButton.top - statusBarHeight) * 2) * (750 / windowWidth);
  // // 5.导航栏与状态栏拉开距离  margin-top: statusBarTop + 'rpx'; 
  let statusBarTop = statusBarHeight * (750 / windowWidth);
  infoData.height = navHeight
  infoData.marginTop = statusBarTop
  return infoData
}

//提示弹窗
const tip = (content,type) =>{
  wx.showModal({
    title: '提示',
    content: content,
    success (res) {
      if (res.confirm) {
        console.log('用户点击确定')
        if(type==1){
          wx.navigateBack({
            delta: 1
          })
        }
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

/**
 * 身份证
 */
const validateidcard=(idCard)=>{

  //15位和18位身份证号码的正则表达式

  var regIdCard=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;



  //如果通过该验证，说明身份证格式正确，但准确性还需计算

  if(regIdCard.test(idCard)){

      if(idCard.length==18){

          var idCardWi=new Array( 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ); //将前17位加权因子保存在数组里

          var idCardY=new Array( 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ); //这是除以11后，可能产生的11位余数、验证码，也保存成数组

          var idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和

          for(var i=0;i<17;i++){

              idCardWiSum+=idCard.substring(i,i+1)*idCardWi[i];

          }

          var idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置

          var idCardLast=idCard.substring(17);//得到最后一位身份证号码

          //如果等于2，则说明校验码是10，身份证号码最后一位应该是X

          if(idCardMod==2){

              if(idCardLast=="X"||idCardLast=="x"){

                  //alert("恭喜通过验证啦！");
                  return true

              }else{

                  //alert("身份证号码错误！");
                  return false

              }

          }else{

              //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码

              if(idCardLast==idCardY[idCardMod]){

                  //alert("恭喜通过验证啦！");
                  return true

              }else{

                  // alert("身份证号码错误！");
                  return false

              }

          }

      }

  }else{

      //alert("身份证格式不正确!");
      return false

  }

}

//版本比对
const compareVersion=function(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

const formatsDates = (date) => {

  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  return month +'月'+day+'日 ' + [hour, minute].map(formatNumber).join(':')
  
}


module.exports = {
  formatTime,
  todayTiem,
  timeState,
  tiemString,
  locationData,
  formatDate,
  formatGetDate,
  formatDateDays,
  formatDateSplicing,
  capsuleData,
  reverseLocationData,
  tip,
  chooseLocationData,
  validateidcard,
  isValidDateRange,
  isValidDateRangeDay,
  formatDateymd,
  compareVersion,
  formatsDates
}